<?php
namespace app\admin\controller;

use app\admin\exception\AdminException;
use think\Request;


class Notice extends Admin
{

    public function initialize() {
        parent::initialize();
        $this->service = model('notice/notice', 'service');
    }
    /**
     * 
     * @rank 1
     */
    public function index(Request $request)
    {

        $maps = [];
        $maps['type'] = $request->param('type');
        $maps['keywords'] = $request->param('keywords');
        $list = $this->service->lists($maps,'create_time DESC',$this->page,$this->limit);
        return $this->render('index', [
            'list' => $list,
        ]);
    }

    /**
     *
     */
    public function create()
    {
        return $this->render('create');
    }

    /**
     * 
     */
    public function edit($id)
    {
        $info = $this->service->detail($id);

        if (!$info) {
            $this->error('公告信息不存在');
        }
        return $this->render('edit', [
            'info' => $info,
        ]);
    }

    /**
     * 
     */
    public function save(Request $request)
    {
        if (empty($request->post('title'))) {
            return json()->data(['code' => 1, 'message' => '标题不能为空']);
        }

        $data = [
            'title' => $request->post('title'),
            'content' => $request->post('content'),
            'status' => $request->post('status'),
        ];
        $result = $this->service->create($data);

        if (!$result) {
            throw new AdminException($this->service->getError());
        }

        return json(['code' => 0, 'toUrl' => url('/admin/notice'), 'message' => '创建成功']);
    }

    /**
     *
     */
    public function update(Request $request, $id)
    {
        if (empty($request->post('title'))) {
            return json()->data(['code' => 1, 'message' => '标题不能为空']);
        }  
        
        $info = $this->service->detail($id);
        if (!$info) {
            $this->error('公告信息不存在');
        }
        $data = [
            'title' => $request->post('title'),
            'content' => $request->post('content'),
            'status' => $request->post('status'),
        ];
        $result = $this->service->edit($id,$data);

        if (!$result) {
            throw new AdminException($this->service->getError());
        }

       return json(['code' => 0, 'toUrl' => url('/admin/notice'), 'message' => '编辑成功']);

    }
    /**
     *
     */
    public function delete($id)
    {
        $result = $this->service->destroy($id);
        if (!$result) {
            throw new AdminException($this->service->getError());
        }

        return json(['code' => 0, 'message' => '删除成功']);
    }
}